package com.lanji.sensitive.services.impl;

import com.lanji.sensitive.config.SensitiveWordsConfig;
import com.lanji.sensitive.entity.request.DocRequest;
import com.lanji.sensitive.entity.response.SensitiveDataRes;
import com.lanji.sensitive.mapper.SensitiveWordsMapper;
import com.lanji.sensitive.services.SensitiveService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Twilight
 * @desc
 * @createTime 2021-01-27-20:20
 */
@Slf4j
@Service
public class SensitiveServiceImpl implements SensitiveService {

    @Autowired
    private SensitiveWordsConfig sensitiveWordsConfig;

    @Resource
    private SensitiveWordsMapper sensitiveWordsMapper;

    @Override
    public List<SensitiveDataRes> parseDoc(DocRequest docRequest) {
        List<String> words;
        if (sensitiveWordsConfig.getYamlConfig()) {
            words = sensitiveWordsConfig.getWords();
        } else {
            words = sensitiveWordsMapper.selectAllWords();
        }

//        String[] split = docStr.split("\\p{P}");
        String[] split = docRequest.getDocStr().split("\\n");

        List<SensitiveDataRes> sensitiveDataRes = Stream.of(split)
                .filter(Objects::nonNull)
                .filter(s -> !StringUtils.isEmpty(s.trim())).map(s -> {
                    SensitiveDataRes sd = new SensitiveDataRes();
                    List<String> sw = words.stream().filter(s::contains).collect(Collectors.toList());
                    for (String word : words) {
                        s = s.replaceAll(word, "<font color=\"#f9963b\">" + word + "</font>");
                    }
                    sd.setParagraph(s).setSensitiveWord(sw);
                    return sd;
                }).collect(Collectors.toList());

        return sensitiveDataRes;
    }
}
